import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import { useAppStore } from '@/store/app'
import { getToken } from '@/utils/auth'

// 配置 NProgress
NProgress.configure({
  showSpinner: false,
  minimum: 0.2,
  easing: 'ease',
  speed: 500
})

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '学生登录',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: {
      title: '学生注册',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: () => import('@/views/ForgotPassword.vue'),
    meta: {
      title: '忘记密码',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/',
    component: () => import('@/layouts/BasicLayout.vue'),
    redirect: '/dashboard',
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: {
          title: '学习首页',
          icon: 'House',
          affix: true
        }
      },
      {
        path: 'courses',
        name: 'Courses',
        component: () => import('@/views/courses/index.vue'),
        meta: {
          title: '我的课程',
          icon: 'Reading'
        },
        children: [
          {
            path: '',
            name: 'CourseList',
            component: () => import('@/views/courses/CourseList.vue'),
            meta: {
              title: '课程列表'
            }
          },
          {
            path: ':id',
            name: 'CourseDetail',
            component: () => import('@/views/courses/CourseDetail.vue'),
            meta: {
              title: '课程详情',
              hideInMenu: true
            }
          },
          {
            path: ':id/study',
            name: 'CourseStudy',
            component: () => import('@/views/courses/CourseStudy.vue'),
            meta: {
              title: '课程学习',
              hideInMenu: true,
              fullscreen: true
            }
          }
        ]
      },
      {
        path: 'exams',
        name: 'Exams',
        component: () => import('@/views/exams/index.vue'),
        meta: {
          title: '考试中心',
          icon: 'Edit'
        },
        children: [
          {
            path: '',
            name: 'ExamList',
            component: () => import('@/views/exams/ExamList.vue'),
            meta: {
              title: '考试列表'
            }
          },
          {
            path: ':id',
            name: 'ExamDetail',
            component: () => import('@/views/exams/ExamDetail.vue'),
            meta: {
              title: '考试详情',
              hideInMenu: true
            }
          },
          {
            path: ':id/take',
            name: 'TakeExam',
            component: () => import('@/views/exams/TakeExam.vue'),
            meta: {
              title: '参加考试',
              hideInMenu: true,
              fullscreen: true
            }
          },
          {
            path: ':id/result',
            name: 'ExamResult',
            component: () => import('@/views/exams/ExamResult.vue'),
            meta: {
              title: '考试结果',
              hideInMenu: true
            }
          }
        ]
      },
      {
        path: 'practice',
        name: 'Practice',
        component: () => import('@/views/practice/index.vue'),
        meta: {
          title: '练习中心',
          icon: 'Notebook'
        },
        children: [
          {
            path: '',
            name: 'PracticeList',
            component: () => import('@/views/practice/PracticeList.vue'),
            meta: {
              title: '练习列表'
            }
          },
          {
            path: ':id',
            name: 'PracticeDetail',
            component: () => import('@/views/practice/PracticeDetail.vue'),
            meta: {
              title: '练习详情',
              hideInMenu: true
            }
          },
          {
            path: ':id/start',
            name: 'StartPractice',
            component: () => import('@/views/practice/StartPractice.vue'),
            meta: {
              title: '开始练习',
              hideInMenu: true,
              fullscreen: true
            }
          }
        ]
      },
      {
        path: 'grades',
        name: 'Grades',
        component: () => import('@/views/grades/index.vue'),
        meta: {
          title: '成绩查询',
          icon: 'DataAnalysis'
        },
        children: [
          {
            path: '',
            name: 'GradeList',
            component: () => import('@/views/grades/GradeList.vue'),
            meta: {
              title: '成绩列表'
            }
          },
          {
            path: ':id',
            name: 'GradeDetail',
            component: () => import('@/views/grades/GradeDetail.vue'),
            meta: {
              title: '成绩详情',
              hideInMenu: true
            }
          }
        ]
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: {
          title: '个人中心',
          icon: 'User'
        },
        children: [
          {
            path: '',
            name: 'ProfileInfo',
            component: () => import('@/views/profile/ProfileInfo.vue'),
            meta: {
              title: '个人信息'
            }
          },
          {
            path: 'settings',
            name: 'ProfileSettings',
            component: () => import('@/views/profile/ProfileSettings.vue'),
            meta: {
              title: '账户设置'
            }
          },
          {
            path: 'study-record',
            name: 'StudyRecord',
            component: () => import('@/views/profile/StudyRecord.vue'),
            meta: {
              title: '学习记录'
            }
          }
        ]
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: {
      title: '页面不存在',
      hideInMenu: true
    }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/403.vue'),
    meta: {
      title: '访问被拒绝',
      hideInMenu: true
    }
  },
  {
    path: '/500',
    name: 'ServerError',
    component: () => import('@/views/error/500.vue'),
    meta: {
      title: '服务器错误',
      hideInMenu: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  try {
    const userStore = useUserStore()
    const appStore = useAppStore()
    
    // 设置页面标题
    const title = to.meta?.title
    if (title) {
      document.title = `${title} - 学生学习平台`
    } else {
      document.title = '学生学习平台'
    }
    
    // 检查是否需要认证
    const requiresAuth = to.meta?.requiresAuth !== false
    const token = getToken()
    
    if (requiresAuth) {
      if (!token) {
        // 未登录，跳转到登录页
        ElMessage.warning('请先登录')
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
        return
      }
      
      // 检查用户信息
      if (!userStore.userInfo) {
        try {
          await userStore.getUserInfo()
        } catch (error) {
          console.error('获取用户信息失败:', error)
          ElMessage.error('获取用户信息失败，请重新登录')
          await userStore.logout()
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
          return
        }
      }
      
      // 检查权限
      const hasPermission = await userStore.checkPermission(to.meta?.permission)
      if (!hasPermission) {
        ElMessage.error('您没有访问该页面的权限')
        next('/403')
        return
      }
    } else {
      // 不需要认证的页面，如果已登录则跳转到首页
      if (token && (to.path === '/login' || to.path === '/register')) {
        next('/')
        return
      }
    }
    
    // 更新应用状态
    appStore.setCurrentRoute(to)
    
    next()
  } catch (error) {
    console.error('路由守卫错误:', error)
    ElMessage.error('页面加载失败，请稍后重试')
    next('/500')
  }
})

router.afterEach((to, from) => {
  // 结束进度条
  NProgress.done()
  
  // 页面访问统计
  if (import.meta.env.PROD) {
    // 这里可以添加页面访问统计代码
    console.log('页面访问:', to.path)
  }
})

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  NProgress.done()
  ElMessage.error('页面加载失败，请刷新重试')
})

export default router

// 导出路由配置供其他地方使用
export { routes }